
const billService = require('../services/bill');
const moment = require('moment');

function select_data(date, list, type_name) {
  const len = date.split('-').length
  let date_unit = 'YYYY'
  if (len === 2) date_unit += '-MM'
  if (len === 3) date_unit += '-MM-DD'
  let _list = list.filter(item => {
    // 将以秒为单位的时间戳改为毫秒的
    let item_date = (item.date + '000').substring(0, 13)
    item_date = moment(+item_date).format(date_unit)
    // 如果没传date ，返回所有数据
    if (!date) item_date = date
    if (type_name === 'all')
      return item_date === date
    else
      return item_date === date && type_name === item.type_name
  })
  return _list
}

function expense_income(_list) {
  const totalExpense = _list.reduce((cur, item) => {
    const type = +(item.record_type)
    if (type === -1) {
      cur += +(item.amount)
      return cur
    }
    return cur
  }, 0)

  const totalIncome = _list.reduce((cur, item) => {
    const type = +(item.record_type)
    if (type === 1) {
      cur += +(item.amount)
      return cur
    }
    return cur
  }, 0)

  return {totalExpense, totalIncome}
}

class BillController {
  async add(req, res) {
    let { record_type, amount, type_name, type_id, date, remark = '' } = req.body;
    if (!record_type || !amount || !type_name || !type_id || !date)
      return res.send({ 'state': 2, 'info': '参数错误或不完整，请检查字段' })
    
    const user_id = req.user._id.toString()
    const result = await billService.add({
      record_type, amount, type_name, type_id, date, remark,user_id
    })
    if(result)
      res.send({ 'state': 0, 'info': '新增账单数据成功' })
    else
      res.send({ 'state': 1, 'info': '获取账单列表错误，请联系系统管理员' })
  }

  async delete(req, res) {
    const { bill_id } = req.body;
    const result = await billService.delete(bill_id)
    if(result)
      res.send({ 'state': 0, 'info': '删除记录成功' })
    else
      res.send({ 'state': 1, 'info': '删除记录数据错误，可能是当前bill_id不存在于数据库，请联系系统管理员' })
  }

  async list(req, res) {
    const user_id = req.user._id.toString()
    let { date='', page = 1, page_size = 5, type_name = 'all'} = req.body;
    const list = await billService.getList(user_id)
    
    const _list = select_data(date, list, type_name)
    let listMap = _list.reduce((cur, item) => {
      delete item.user_id
      delete item.createdAt
      delete item.updatedAt
      let date = (item.date + '000').substring(0, 13)
      date = moment(+date).format('YYYY-MM-DD')
      if (cur && cur.length) {
        const index = cur.findIndex(item => item.date == date)
         // 如果能在累加的数组中找到当前项日期 date，那么在数组中的加入当前项到 bills 数组
        if (index > -1) 
          cur[index].bills.push(item)
        // 如果在累加的数组中找不到当前项日期的，那么再新建一项
        else
          cur.push({
            date,
            bills: [item]
          })
      }
      // 如果 curr 为空数组，则默认添加第一个账单项 item ，格式化为下列模式
      else
        cur.push({
          date,
          bills: [item]
        })
      return cur
    }, []).sort((a, b) => moment(b.date) - moment(a.date))

    const filterListMap = listMap.slice((page - 1) * page_size, page * page_size)
    
    // let __list = list.filter(item => {
    //   let item_date = (item.date + '000').substring(0, 13)
    //   item_date = moment(+item_date).format(date_unit)
    //   if (!date) item_date = date
    //   return item_date === date
    // })
    const { totalExpense, totalIncome } = expense_income(_list)
    const result = {
      totalExpense, // 当月支出
      totalIncome, // 当月收入
      totalPage: Math.ceil(listMap.length / page_size), // 总分页
      list: filterListMap || [] // 格式化后，并且经过分页处理的数据
    }

    if(list)
      res.send({ 'state': 0, 'info': result })
    else
      res.send({ 'state': 1, 'info': '获取账单列表错误，请联系系统管理员' })
  }

  async detail(req, res) {
    let { bill_id } = req.body
    if (!bill_id) return res.send({ 'state': 1, 'info': '需要传bill_id' })
    const result = await billService.detail(bill_id.toString())
    if(result)
      res.send({ 'state': 0, 'info': result })
    else
      res.send({ 'state': 1, 'info': '获取记录数据错误，请联系系统管理员' })
  }
  async edit(req, res) {
    const { bill_id, record_type, amount, type_name, type_id, date, remark } = req.body;
    if (!bill_id) return res.send({ 'state': 1, 'info': '需要传bill_id' })
    const billInfo = await billService.detail(bill_id.toString());

    if (record_type) billInfo.record_type = record_type
    if (amount) billInfo.amount = amount
    if (type_name) billInfo.type_name = type_name
    if (type_id) billInfo.type_id = type_id
    if (date) billInfo.date = date
    if (remark) billInfo.remark = remark

    const result = await billService.edit(billInfo);

    if (result) {
      return res.send({ 'state': 0, 'info': '账单信息更新成功' });
    }
    else
      return res.send({ 'state': 1, 'info': '账单信息更新错误，请联系后台管理员' });
  }
  async statistics_info(req, res) {
    let { date='', type_name = 'all'} = req.body;
    const user_id = req.user._id.toString();
    let list = await billService.getList(user_id)
    const _list = select_data(date, list, type_name)
    const { totalExpense, totalIncome } = expense_income(_list)
    let total_data = _list.reduce((cur, data) => {
      const index = cur.findIndex(item => item.type_name === data.type_name)
      if (index === -1) {
        cur.push({
          type_name: data.type_name,
          record_type: data.record_type,
          number: +(data.amount)
        })
      }
      else {
        cur[index].number += Number(data.amount)
      }
      return cur
    }, [])
    total_data = total_data.map(item => {
      item.number = Number(Number(item.number).toFixed(2))
      return item
    })
    return res.send({
      totalExpense: Number(totalExpense).toFixed(2),
      totalIncome: Number(totalIncome).toFixed(2),
      total_data: total_data || [],
    })
  }
}

// 导出 Controller 的实例
module.exports = new BillController();
